import { computed, defineComponent } from 'vue';

import { SchemaFormPropsDefine, SchemaType } from './types';
import { retrieveSchema } from './utils';

import StringField from './fields/StringField';
import NumberField from './fields/NumberField';
import ObjectField from './fields/ObjectField';
import ArrayField from './fields/ArrayField';

export default defineComponent({
  name: 'SchemaItem',
  props: SchemaFormPropsDefine,
  setup(props) {
    // 解析 schema 并传递到具体的实现组件内部。
    const retrievedSchemaRef = computed(() => {
      const { schema, rootSchema, value } = props;
      return retrieveSchema(schema, rootSchema, value);
    });
    return () => {
      // type 变了的时候需要重新渲染其他的 field组件
      const type = props.schema.type;
      let Component: any = null;
      const retrievedSchema = retrievedSchemaRef.value;
      // 把
      switch (type) {
        case SchemaType.string:
          Component = StringField;
          break;
        case SchemaType.number:
          Component = NumberField;
          break;
        case SchemaType.object:
          Component = ObjectField;
          break;
        case SchemaType.array:
          Component = ArrayField;
          break;
        default:
          console.warn(`${type} 不支持`);
      }
      return <Component {...props} schema={retrievedSchema} />;
    };
  },
});
